import { Component, OnInit, Injector, ViewChild, Pipe } from '@angular/core';
import { DetailBase } from 'app/modules/base/detail-base';
import { combineLatest, map, switchMap, tap, throwIfEmpty } from 'rxjs/operators';
import {
  Computer,
  ComputerService,
  ComputerStatus,
  ComputerInfo,
  Personnel,
} from '../../services/computer.service';
import { SoftwareService } from 'app/modules/software/services/software.service';
import { AddPeopleComponent } from '../add-people/add-people.component';
import { CertificationService } from '../../services/certification.service';
import { MySelection } from 'app/modules/base/selection';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { ListOption } from 'app/modules/base/api-base';







@Component({
  selector: 'm-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss'],
})
export class DetailsComponent extends DetailBase implements OnInit {
  selection = new MySelection<Personnel>('id');
  terminalCate = [
    { value: 0, name: '个人设备' },
    { value: 1, name: '公共设备' }
  ]
  activeAreaID: number = 0;
  form = this.fb.group({ id: [''], name: [''], remark: [''], device_type: [0] });
  details$ = this.getData<Computer>('details');
  installed$ = this.details$.pipe(map(c => this.computerService.installed(c.id)));
  // person$=this.details$.pipe(switchMap(c => this.computerService.terminal_per(c.id).list({scope:0})))
  query$ = new BehaviorSubject<ListOption>({ page: 1 });
  // tag
  person$:any;
  
  // deviceType$ = new BehaviorSubject(this.form.controls['device_type'].value);
  edit = false;
  Sortable = [
    'area_count',
    'full_name',
    'id',
    'job_number',
    'online',
    'remark',
    'status',
    'update_admin_username',
    'updated_at',
    'utype',
  ];
  constructor(
    private injector: Injector,
    private computerService: ComputerService,
    private softwareService: SoftwareService,
    private certifi: CertificationService,
  ) {
    super(injector);
    this.query$.pipe(
      tap(()=>{}),
      switchMap(c => {
       return this.computerService.terminal_per(this.route.snapshot.data['details'].id).list({ scope: 0 });
      }),
    ).subscribe(res=>{
      this.person$  = res
    });
  }
  ComputerStatus = ComputerStatus;
  usedLogger$ = this.details$.pipe(map(detail => this.computerService.pc_use(detail.id)));
  ngOnInit() {
    this.activeAreaID = this.computer.device_type ;
    this.form.patchValue(this.computer);
  }
  get computer() {
    return this.route.snapshot.data['details'] as Computer;
  }
  handleSave() {
    let currentRoutePath = window.location.pathname + window.location.search


    this.router.navigateByUrl('/empty')
    // this.router.navigateByUrl(currentRoutePath)

  }
  async status(id: number, status: ComputerStatus) {
    if (
      (await this.sweet.confirm(`确定要${status === ComputerStatus.Enable ? '启用' : '停用'}吗？`))
        .dismiss
    ) {
      return;
    }
    await this.computerService.batch('status', status, [id]);
    this.reload();
  }
  async delete(computer: ComputerInfo) {
    const result = await this.sweet.confirm(`确定要删除终端${computer.name}吗？`);
    if (result.value) {
      await this.computerService.delete([computer.id]);
      this.back();
    }
  }
  async upgrade() {
    await this.computerService.upgrade({ computerIDs: [this.computer.id] });
    this.reload();
  }
  async upgradeSoftware(...sid: number[]) {
    return this.softwareService.upgrade({ softwareIDs: sid, computerIDs: [this.computer.id] });
  }
  async save() {
    await this.computerService.update(this.form.value);
    this.edit = false;
    this.query$.next({page: 1});
    //this.deviceType$.next(this.form.controls['device_type'].value);
    this.reload();
  }

  ssh(computer: Computer) {
    window.open(
      `/ssh/${computer.name}?id=${computer.id}`,
      `Web SSH`,
      'width=1100,height=600,fullscreen=3',
    );
  }
  onActiveAreaID(id) {
    if (this.activeAreaID == id) {
      return;
    }
    this.activeAreaID = id;
  }
  //添加可登录用户
  async addPerson() {
    const result = await this.dialog.open(AddPeopleComponent, { width: '1120px' }).afterClosed().toPromise();
    if (result) {
      this.query$.next({});
    }
  }

  //移除可登陆人员
  async deletePersonnel(list, person) {
    if (!list.length) {
      list = [...this.selection.selected];
    }
    const result = await this.sweet.confirm(`确定要删除[${list.map(pc => pc.full_name).join(',')}]吗？`);
    if (result.dismiss) {
      return;
    }
    if (person.total > list.length) {
      const param = {
        list: list.map(pc => pc.id),
        pc_id: this.route.snapshot.data['details'].id
      }
      await this.certifi.delUser(param);
      this.query$.next({});
    } else {
      this.toaster.warn('请至少保留一位允许登陆用户');
      this.query$.next({});
    }
  }
}
